/**
 * 用户认证相关的Composable
 */
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth.store'

// 用户接口类型定义
export interface User {
  userId: string;
  username: string;
  avatar?: string;
}

// API基础URL
const API_URL = 'http://localhost:8080/api';

export function useAuth() {
  const authStore = useAuthStore()
  const router = useRouter()
  const loading = ref(false)
  const error = ref('')

  /**
   * 用户登录
   * @param account 账号/邮箱/手机号
   * @param password 密码
   */
  async function login(account: string, password: string) {
    loading.value = true
    error.value = ''
    
    try {
      const response = await fetch(`${API_URL}/auth/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ account, password })
      })
      
      const data = await response.json()
      
      if (!response.ok) {
        throw new Error(data.message || '登录失败')
      }
      
      // 保存用户信息和令牌
      authStore.setUser(data.data)
      authStore.setToken(data.token)
      
      // 跳转到首页
      router.push('/')
      return true
    } catch (err: any) {
      error.value = err.message
      return false
    } finally {
      loading.value = false
    }
  }

  /**
   * 用户注册
   * @param userData 用户注册数据
   */
  async function register(userData: {
    username: string;
    email: string;
    phone?: string;
    password: string;
  }) {
    loading.value = true
    error.value = ''
    
    try {
      const response = await fetch(`${API_URL}/auth/register`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(userData)
      })
      
      const data = await response.json()
      
      if (!response.ok) {
        throw new Error(data.message || '注册失败')
      }
      
      // 保存用户信息和令牌
      authStore.setUser(data.data)
      authStore.setToken(data.token)
      
      // 跳转到首页
      router.push('/')
      return true
    } catch (err: any) {
      error.value = err.message
      return false
    } finally {
      loading.value = false
    }
  }

  /**
   * 退出登录
   */
  function logout() {
    authStore.logout()
    router.push('/login')
  }

  /**
   * 检查用户是否已登录
   */
  function isAuthenticated() {
    return !!authStore.token
  }

  return {
    login,
    register,
    logout,
    isAuthenticated,
    loading,
    error
  }
}